<?php

// 初始化程序执行代码


// 格式化章节数据
function dr_format_son_list($list, $type) {

    if (!$list) {
        return [];
    }

    $type = dr_string2array($type);
    if (!$type) {
        $type = [
            0 => '',
        ];
    }

    $rt = [];
    foreach ($type as $tid => $name) {

        if (!isset($rt[$tid])) {
            $rt[$tid] = [];
        }

        if ($list) {
            foreach ($list as $i => $t) {
                if ($t['tid'] == $tid) {
                    $rt[$tid][] = $t;
                    unset($list[$i]);
                }
            }
        }
    }

    return $rt;
}

function dr_son_type($type) {

    $type = dr_string2array($type);
    if (!$type) {
        $type = [
            0 => dr_lang('基本内容'),
        ];
    }

    return $type;
}

if (!function_exists('dr_son_url')) {
    function dr_son_url($data) {
        return '/index.php?s=book&c=son&m=show&id='.$data['id'];
    }
}

// 是否存在中 1收藏了 2没有收藏
function dr_is_book_cart($dir, $id, $uid = 0) {

    !$uid && $uid = \Phpcmf\Service::C()->uid;
    if (!$uid) {
        return 0;
    } elseif (!$dir) {
        return 0;
    }

    return \Phpcmf\Service::M()->db->table(SITE_ID.'_'.$dir.'_cart')->where('uid', $uid)->where('cid', $id)->countAllResults();
}

// 是否购买了
function dr_is_book_buy($dir, $id, $uid = 0) {

    !$uid && $uid = \Phpcmf\Service::C()->uid;
    if (!$uid) {
        return 0;
    } elseif (!$dir) {
        return 0;
    } elseif (!$id) {
        return 0;
    }

    return \Phpcmf\Service::M()->db->table(SITE_ID.'_'.$dir.'_buy')->where('uid', $uid)->where('cid', $id)->countAllResults();
}